﻿using System;
using System.Linq;
using System.Text;
using System.Security.Cryptography;

namespace TowerCraneMonitorClient.NetClient
{
    public class ClientHelper
    {
        const string TestHostAddress = "http://test.lemcd.tower.com";
        const string HostAddress = "http://lemcd.tower.com";


        static readonly long baseTimeTicks = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).Ticks;
        const string letters = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
        const int randomCodeLength = 12;
        const string secretKey = "8Yn8vptQYzsx3WX9nV72NyB4Q3p6U8";
        const string keyId = "84983712-7cda-11e7-857d-00163e32d704";

        static readonly Random random = new Random();


        /// <summary>
        /// 服务器主机地址
        /// </summary>
        public const string Host = TestHostAddress;

        public static string GetUploadURL(IUploadable o) { return Host + o.UploadPath; }

        public string KeyId { get => keyId; }
        public long TimeStamp { get; }
        public string RandomCode { get; }
        public string Signature { get; }

        public ClientHelper() : this(UnixTimeStamp.Now.ToLong(), GetRandomCode()) { }

        public ClientHelper(long timeStamp, string randomCode)
        {
            TimeStamp = timeStamp;
            RandomCode = randomCode;
            Signature = GetSignature();
        }


        public static string GetRandomCode()
        {
            var r = "";
            for (int i = 0; i < randomCodeLength; i++)
                r += letters[random.Next(0, letters.Length - 1)];
            return r;
        }


        string GetSignature()
        {
            using (var sha1 = new SHA1CryptoServiceProvider())
                return sha1.ComputeHash(signatureBytes())
                    .Select(b => b.ToString("x2"))
                    .Aggregate("", (p, s) => p + s);

            byte[] signatureBytes() => Encoding.UTF8.GetBytes(signatureString());
            string signatureString() => $"{RandomCode}_{TimeStamp}_{secretKey}";
        }

    }
}
